package cn.xshi.omp.collect;
import cn.xshi.omp.model.OMPRedisConfig;
import cn.xshi.omp.model.OMPRedisInfo;
import cn.xshi.omp.model.OMPRedisMain;
import cn.xshi.omp.service.OMPRedisConfigService;
import cn.xshi.omp.service.OMPRedisInfoService;
import cn.xshi.omp.service.OMPRedisMainService;
import cn.xshi.omp.util.JedisUtil;
import cn.xshi.common.idgeneration.SnowflakeIdWorker;
import cn.xshi.common.util.JsonUtil;
import cn.xshi.common.util.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
 * @Desc Redis信息监控
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
@Order(1)
public class RedisEvent implements CommandLineRunner {

    @Resource
    SnowflakeIdWorker snowflakeIdWorker;

    @Resource
    OMPRedisConfigService redisConfigService;

    @Resource
    OMPRedisMainService ompRedisMainService;

    @Resource
    OMPRedisInfoService ompRedisInfoService;

    @Resource
    JedisUtil jedisUtil;

//
//    @Scheduled(cron="*/30 * * * * *")
//    public void execute() {
//        try {
//            Map<String,Object> condition = new HashMap<>();
//            List<OMPRedisConfig> ompRedisConfigs = redisConfigService.getRedisConfigListByCondition(condition);
//            for(OMPRedisConfig ompRedisConfig: ompRedisConfigs){
//                single(ompRedisConfig);
//            }
//        }catch (Exception e){
//            log.error("采集Reids信息异常：{}",e);
//        }
//    }

    @Override
    public void run(String... args){
        new Thread(new RedisEventWorker()).start();
    }

    private void execute() throws Exception {
        while (true){
            try {
                Map<String,Object> condition = new HashMap<>();
                List<OMPRedisConfig> ompRedisConfigs = redisConfigService.getRedisConfigListByCondition(condition);
                for(OMPRedisConfig ompRedisConfig: ompRedisConfigs){
                    single(ompRedisConfig);
                }
            }catch (Exception e){
                log.error("采集Reids信息异常：{}",e);
            }finally {
                Thread.sleep(5000);
            }
        }
    }

    /**
     *
     */
    class RedisEventWorker implements Runnable{
        public void run() {
            try {
                execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 单机监控
     */
    public void single(OMPRedisConfig ompRedisConfig){
        try {
            Jedis jedis = jedisUtil.getPoolJedis(ompRedisConfig);
            if(null != jedis){
                String info = jedis.info();
                jedisUtil.closePoolJedis(jedis);//释放
                OMPRedisInfo redisInfo = jedisUtil.convertInfo(info);
                OMPRedisMain ompRedisMain = new OMPRedisMain();
                ompRedisMain.setId(""+snowflakeIdWorker.nextId());
                ompRedisMain.setConfigId(ompRedisConfig.getId());
                ompRedisMain.setInfo(JsonUtil.toFastJson(redisInfo));
                ompRedisMain.setCreateTime(DateUtil.getDate());
                ompRedisMainService.addRedisMain(ompRedisMain);
                redisInfo.setId(""+snowflakeIdWorker.nextId());
                redisInfo.setMainId(ompRedisMain.getId());
                redisInfo.setConfigId(ompRedisConfig.getId());
                redisInfo.setCreateTime(DateUtil.getDate());
                ompRedisInfoService.addRedisInfo(redisInfo);
            }
        }catch (Exception e){
            log.error("采集Reids信息逻辑异常：{}-{}",e,ompRedisConfig);
        }
    }

    /**
     * 集群监控
     */
    public void cluster(OMPRedisConfig redisConfig){
        Jedis jedis = jedisUtil.getPoolJedis(redisConfig);
        String info = jedis .clusterNodes();
        jedisUtil.closePoolJedis(jedis);//释放
//        Map<String,Properties> map = new HashMap<>();
//        RedisClusterConnection clusterConnection = redisTemplate.getRequiredConnectionFactory().getClusterConnection();
//        Iterable<RedisClusterNode> clusterNodes =  clusterConnection.clusterGetNodes();
//        for(RedisClusterNode node : clusterNodes){
//            Properties info = clusterConnection.info(new RedisClusterNode(node.getHost(),node.getPort()));
//            monitor(info,node.getHost());
//            map.put(node.getHost(),info);
//        }
    }

    /**
     *
     * @param info
     * @param host
     */
    private void monitor(Properties info, String host){
        log.info("节点--host：{}--info:{}",host,info);
//        String totalMemStr = info.getProperty("total_system_memory");
//        String usedMemStr =  info.getProperty("used_memory_rss");
//
//        //总内存
//        Long totalMem = Long.parseLong(totalMemStr);
//
//        //使用内存
//        Long userdMem =  Long.parseLong(usedMemStr);
//        int mem = Math.round(userdMem*100/totalMem);
//
//        String usedCpuSysStr = info.getProperty("used_cpu_sys");
//        String usedCpuSysChdStr =  info.getProperty("used_cpu_sys_children");
//        String usedCpuUserStr = info.getProperty("used_cpu_user");
//        String usedCpuUserChdStr =  info.getProperty("used_cpu_user_children");
//
//        Double usedCpuSys = Double.parseDouble(usedCpuSysStr);
//        Double usedCpuSysChd =  Double.parseDouble(usedCpuSysChdStr);
//        Double usedCpuUser =  Double.parseDouble(usedCpuUserStr);
//        Double usedCpuUserChd =  Double.parseDouble(usedCpuUserChdStr);
    }
}
